package com.gxatek.cockpit.dvr.service;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.gxatek.cockpit.dvr.service.view.CustomLineChart;
import com.gxatek.cockpit.dvr.service.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用MPAndroidChart显示加速度的数据，数据是之前在androidStudio里输出的，copy到了文件里，然后读取文件，显示x,y,z的值
 *
 */
public class SecondActivity extends AppCompatActivity implements SensorEventListener {
    private SensorManager sensorManager;
    private Sensor accelerometer;
    String TAG = "MainActivity";

    List<Item> list = new ArrayList<>();
    List<Float>xDataList = new ArrayList<>();
    List<Float>yDataList = new ArrayList<>();
    List<Float>zDataList = new ArrayList<>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    CustomLineChart markerView, yMarkView,zMarkView;
    public static int MSG_LOAD_DATA_FINISHED = 10;
    boolean isRecordStart = false;
    Button btnRecord;
    TextView tvResult;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkCallingPermission(Manifest.permission.BODY_SENSORS) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.BODY_SENSORS}, 10);
            }
        }
        tvResult = findViewById(R.id.tvClickResult);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        markerView = findViewById(R.id.xMarkerView);
        markerView.setLineColor(Color.BLACK);
        markerView.setPointColor(Color.RED);
        markerView.setPointSize(1);
        markerView.setOnPointClickListener(new CustomLineChart.PointClickListener(){
            @Override
            public void onClick(int index) {
                Item item = list.get(index);
                if(item!=null){
                    float x = item.values[0];
                    tvResult.setText("x: "+x+"\t时间："+sdf.format(item.date));
                }
            }
        });

        yMarkView = findViewById(R.id.yMarkerView);
        yMarkView.setLineColor(Color.BLACK);
        yMarkView.setPointColor(Color.RED);
        yMarkView.setPointSize(1);
        yMarkView.setOnPointClickListener(new CustomLineChart.PointClickListener(){
            @Override
            public void onClick(int index) {
                Item item = list.get(index);
                if(item!=null){
                    float x = item.values[1];
                    tvResult.setText("y: "+x+"\t时间："+sdf.format(item.date));
                }
            }
        });

        zMarkView = findViewById(R.id.zMarkerView);
        zMarkView.setLineColor(Color.BLACK);
        zMarkView.setPointColor(Color.RED);
        zMarkView.setPointSize(1);
        zMarkView.setOnPointClickListener(new CustomLineChart.PointClickListener(){
            @Override
            public void onClick(int index) {
                Item item = list.get(index);
                if(item!=null){
                    float x = item.values[2];
                    tvResult.setText("z: "+x+"\t时间："+sdf.format(item.date));
                }
            }
        });

        findViewById(R.id.btnResetClick).setOnClickListener(v->{
            markerView.resetClickLine();
            yMarkView.resetClickLine();
            zMarkView.resetClickLine();
        });
        btnRecord = findViewById(R.id.btnStartStop);
        btnRecord.setOnClickListener(v->{
            if (!isRecordStart) {//未开始
                Log.e(TAG, "开始采集sensor数据了");
                isRecordStart = true;
                btnRecord.setText(getResources().getString(R.string.sensor_record_stop));
                btnRecord.setTextColor(getResources().getColor(R.color.red));
                startRecordAccelerometer();
                Toast.makeText(this, "数据采集开始！", Toast.LENGTH_SHORT).show();
            } else {
                Log.e(TAG, "结束采集sensor数据了");
                isRecordStart = false;
                btnRecord.setText(getResources().getString(R.string.sensor_record_start));
                btnRecord.setTextColor(getResources().getColor(R.color.white));
                stopRecordAccelerometer();
                Toast.makeText(this, "数据采集结束！", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void startRecordAccelerometer() {
        /**
         * 车机上最快好像也就是100ms
         * SENSOR_DELAY_FASTEST 最低延迟 0us，一般不推荐使用，该种模式可能造成手机电力大量消耗，会影响手机性能
         * SENSOR_DELAY_GAME 游戏延迟 20,000 us，一般绝大多数的实时性较高的游戏都使用该级别
         * SENSOR_DELAY_UI 界面延迟 60,000 us ，一般对于屏幕方向自动旋转使用，相对节省电能和逻辑处理，一般游戏开发中我们不使用。
         * SENSOR_DELAY_NORMAL 标准延迟 200,000 us，200ms ，对于一般的简单小游戏可以使用，但过低的采样率可能对一些赛车类游戏有跳帧现象。
         */
        /*int position = spinner.getSelectedItemPosition();
        Log.e(TAG, "position="+position);*/
        sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);

    }



    private void stopRecordAccelerometer() {
        sensorManager.unregisterListener(this);
        //停止流写文件
        isRecordStart = false;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e(TAG, "onRequestPermissionsResult->permissions.length=" + permissions.length + " granted.length=" + grantResults.length);
    }

    @Override
    protected void onResume() {
        super.onResume();
   }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
        //2025-02-25 16:33:33.662 13679-13679/com.senseauto.sensordemo E/MainActivity: length:3 x=1.283292 y=-0.038307227 z=9.758766
        //Log.e(TAG, "length:" + event.values.length + " x=" + x + " y=" + y + " z=" + z);
        if(list.size()>=500){
            list.remove(0);
        }
        list.add(new Item(new float[]{x,y,z}, new Date()));

        if(xDataList.size()>=500){
            xDataList.remove(0);
        }
        xDataList.add(x);
        markerView.setData(xDataList);
        markerView.invalidate();

        if(yDataList.size()>=500){
            yDataList.remove(0);
        }
        yDataList.add(y);
        yMarkView.setData(yDataList);
        yMarkView.invalidate();


        if(zDataList.size()>=500){
            zDataList.remove(0);
        }
        zDataList.add(z);
        zMarkView.setData(zDataList);
        zMarkView.invalidate();
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sensorManager.unregisterListener(this);
    }
}